package com.heima.article.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.IApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmNews;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.*;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author lcz
 * @since 2024-11-17
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {

    private static final int size = 10;

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleContentMapper contentMapper;

    @Autowired
    private ApArticleConfigMapper configMapper;
    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;


    @Override
    public ResponseResult load(ArticleHomeDto dto, Integer type) {
        if (dto.getSize() == null || dto.getSize() < 0) {
            dto.setSize(size);
        }
        if (StringUtils.isEmpty(dto.getTag())) {
            dto.setTag(ArticleConstants.LOADMORE.toString());
        }
        if (dto.getMaxBehotTime() == null) dto.setMaxBehotTime(new Date());
        if (dto.getMinBehotTime() == null) dto.setMinBehotTime(new Date());
        List<ApArticle> apArticles = baseMapper.loadArticleList(dto, type);
        return ResponseResult.okResult(apArticles);
    }

    @Override
    public Long submit(ArticleDto dto) {
        try {
            //保存文章信息表
            ApArticle article = new ApArticle();
            BeanUtils.copyProperties(dto, article);
            article.setStaticUrl(createUrl(dto.getContent()));
            apArticleMapper.insert(article);


            //保存文章内容表
            ApArticleContent articleContent = new ApArticleContent();
            articleContent.setArticleId(article.getId());
            articleContent.setContent(dto.getContent());
            contentMapper.insert(articleContent);

            //保存文章配置表
            ApArticleConfig articleConfig = new ApArticleConfig();
            articleConfig.setArticleId(article.getId());
            articleConfig.setIsDelete(0);
            articleConfig.setIsDown(0);
            articleConfig.setIsComment((int) dto.getDiscuss());
            articleConfig.setIsForward((int) dto.getForward());
            configMapper.insert(articleConfig);

            return article.getId();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private String createUrl(String content) throws Exception {
        Template template = configuration.getTemplate("article.ftl");
        Map<String, Object> map = new HashMap<>();
        map.put("content", JSONArray.parseArray(content));

        StringWriter out = new StringWriter();
        template.process(map, out);
        InputStream is = new ByteArrayInputStream(out.toString().getBytes());
        String fileName = UUID.randomUUID().toString() + ".html";
        String url = fileStorageService.uploadHtmlFile(null, fileName, is);
        return url;

    }


}
